<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2020/4/11
 * Time: 9:20
 */

namespace App\Controller\admin;


use App\Controller\Base;
use App\Lib\Redis;
use App\Lib\Token;
use App\Model\AuAdmin;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class Auth
 * @package App\Controller\admin
 * @Controller(prefix="a")
 */
class AuthController extends Base {

    /**
     * @RequestMapping(path="a",methods="get")
     */
    public function demo() {
        return success('123123');
    }

    /**
     * 登录
     * @RequestMapping(path="login",methods="post")
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    public function login() {
        $account = $this->body('account');
        $pwd = $this->body('pwd');
        if (empty($account) || empty($pwd)) {
            return error('参数错误');
        }
        $info = AuAdmin::query()
            ->where('account', $account)
            ->select('id', 'name', 'status')
            ->first()->toArray();
        if (empty($info)) {
            return error('账号或密码错误');
        }
        if ($info['status'] == 0) {
            return error('账号被禁用，请联系管理员');
        }
        // 查询角色
        if ($info['id'] != 1) {
            $roles = AuAdmin::query()
                ->from('au_admin_role as ar')
                ->join('au_role as r', 'ar.role_id', '=', 'r.id')
                ->where('user_id', $info['id'])
                ->where('status', 1)
                ->pluck('r.id');
        } else {
            $roles = [];
        }
        $token = $this->di->get(Token::class)->admin($info['id'], $info['name'], $roles);
        return success(['ak' => $token]);
    }

    /**
     * 登录信息
     * @Middleware(\App\Middleware\AdminMiddleware::class)
     * @RequestMapping(path="login_info",methods="get")
     */
    public function isLogin() {
        $data = ['menus' => [], 'admin' => []];
        $data['admin'] = $this->request->getAttribute('admin');
        // $data['admin'] = ['id' => 2, 'name' => 123, 'rid' => [3]];
        $redis = Redis::get();
        $all = $redis->get('admin_menus');
        if (empty($all)) {
            $all = [];
        } else {
            $all = json_decode($all, true);
            if ($data['admin']['id'] != 1) {
                $auths = [];
                // 多角色合并权限
                foreach ($data['admin']['rid'] as $role) {
                    $auth = $redis->hGet("ar:{$role}", 'menus');
                    if ($auth) {
                        $auths = array_merge($auths, explode(',', $auth));
                    }
                }
                $auths = array_unique($auths);
                if ($auths) {
                    $menus = $all;
                    foreach ($all as $k1 => $lv1) {
                        foreach ($lv1['children'] as $k2 => $lv2) {
                            $auth = [];
                            foreach ($lv2['auth'] as $k => $val) {
                                if (in_array($k, $auths)) {
                                    $auth[$val] = 1;
                                }
                            }
                            if (empty($auth)) {
                                unset($menus[$k1]['children'][$k2]);
                            } else {
                                $menus[$k1]['children'][$k2]['auth'] = $auth;
                            }
                        }
                        if (empty($menus[$k1]['children'])) {
                            unset($menus[$k1]);
                        }
                    }
                    $all = array_values($menus);
                    unset($menus);
                } else {
                    $all = [];
                }
            } else {
                foreach ($all as &$lv1) {
                    foreach ($lv1['children'] as &$lv2) {
                        $lv2['auth'] = [];
                    }
                }
                $all[] = [
                    'name' => '权限',
                    'path' => 'admin',
                    'ext' => '',
                    'children' => [
                        ['name' => '账号管理', 'path' => 'account', 'ext' => '', 'auth' => [],],
                        ['name' => '角色管理', 'path' => 'role', 'ext' => '', 'auth' => [],],
                        ['name' => '规则管理', 'path' => 'rule', 'ext' => '', 'auth' => [],],
                    ],
                ];
            }
        }
        unset($data['admin']['rid']);
        $data['menus'] = $all;
        return success($data);
    }


    /**
     * 修改密码
     * @Middleware(\App\Middleware\AdminMiddleware::class)
     * @RequestMapping(path="ch_pwd",methods="post")
     * @return array
     */
    public function changePwd() {
        $admin = $this->request->getAttribute('admin');
        $param = [
            'old_password' => $this->body('old_password'),
            'password' => $this->body('password'),
            'password_confirm' => $this->body('password_confirm'),
        ];
        if (empty($param['old_password']) || empty($param['password']) || empty($param['password_confirm'])) {
            return error('非法参数');
        }
        if ($param['password'] != $param['password_confirm']) {
            return error('新密码与确认密码不一致');
        }
        if ($param['password'] == $param['old_password']) {
            return error('新旧密码不能相同');
        }
        $old = AuAdmin::query()
            ->where('id', $admin['id'])
            ->value('password');
        if ($old != saltMd5($param['old_password'])) {
            return error('旧密码错误');
        }
        $r = AuAdmin::query()
            ->where('id', $admin['id'])
            ->update([
                'password' => saltMd5($param['password']),
            ]);
        return $r ? success() : error();
    }


    /**
     * @RequestMapping(path="aa",methods="get")
     */
    public function indexa() {
        $_ENV['APP_DEV'] = $_ENV['APP_DEV'] == 'false' ? 'true' : 'false';
        return ['data' => $_ENV['APP_DEV']];
    }


}
